import React, {
  FC,
  ReactElement,
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
  ReactNode,
} from 'react';
import style from './index.less';
import commonStyle from '@/pages/publicStyle';
import { Steps, Form, Button, Modal } from 'antd';
import {
  CheckCircleFilled,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import './index.less';
import moment from 'moment';
import { dataFormat2 } from '@/untils/dictionaries';
const { mt10, mt20, mr20 } = commonStyle;

const { Step } = Steps;
const { confirm } = Modal;
interface IProp {
  children: ReactNode;
  formData: any;
  disabledFieldList: string[];
  saveFormDataOnField?: () => void;
  stepCurrent: number;
  onStepChange: (stepNo: number) => void;
  initFormCustom: () => void[];
  cancelCallback: () => void;
}
// eslint-disable-next-line react/display-name
const StepForm = forwardRef((props: IProp, ref: unknown): ReactElement => {
  const [form] = Form.useForm();
  const [stepTooltip, setStepTooltip] = useState(''); // 更新时间
  const {
    stepCurrent,
    disabledFieldList,
    formData,
    onStepChange,
    initFormCustom,
    saveFormDataOnField,
    cancelCallback,
  } = props;
  // 下一步
  const goForNext = () => {
    form.validateFields().then();
  };
  // 上一步
  const goForPrev = () => {
    onStepChange(stepCurrent - 1);
  };
  // 取消
  const cancel = () => {
    confirm({
      title: '离开页面前，是否保存当前页面内容?',
      content: '保存后可以再草稿中继续编辑',
      icon: <ExclamationCircleOutlined />,
      okText: '保存并离开',
      okType: 'danger',
      cancelText: '不保存',
      onOk() {
        cancelCallback();
      },
    });
  };
  // 初始化表单方法
  const setFormFields = (fieldObj: unknown) => {
    form.setFieldsValue(fieldObj);
  };
  const fieldsChange = (changedFields: unknown) => {
    setStepTooltip(moment(new Date()).format(dataFormat2));
    let resultData = [];
    resultData = changedFields.map((item: unknown) => {
      return {
        field: item.name[0],
        value: item.value,
      };
    });
    saveFormDataOnField && saveFormDataOnField(resultData);
  };
  // 成功后表头字段
  const getSuccessTitle = () => {
    return (
      <div>
        <CheckCircleFilled style={{ color: '#52c41a', fontSize: '70px' }} />
        <div style={{ ...mt20, fontSize: '18px' }}>新建成功</div>
      </div>
    );
  };
  useImperativeHandle(ref, () => {
    return {
      setFormFields: setFormFields,
    };
  });
  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const formSetObj: any = {};
    for (const key in form.getFieldsValue()) {
      if (!disabledFieldList.some((item) => item === key)) {
        formSetObj[key] = formData[key];
      }
    }
    setFormFields(formSetObj);
    initFormCustom &&
      initFormCustom[stepCurrent] &&
      initFormCustom[stepCurrent]();
  }, [stepCurrent]);
  const {
    stepHeaderBox,
    stepTitleBox,
    stepFormBox,
    actionBtnBox,
    stepTooltipBox,
  } = style;
  return (
    <div>
      <div className={stepHeaderBox}>
        <Steps
          current={props.stepCurrent}
          status={useState}
          type="navigation"
          className="site-navigation-steps"
        >
          <Step title="项目基本信息" />
          <Step title="项目详细信息" />
          <Step title="完成" />
        </Steps>
      </div>
      <div className={stepTitleBox}>
        {props.stepCurrent === 0
          ? '项目基本信息'
          : props.stepCurrent === 1
          ? '项目详细信息'
          : getSuccessTitle()}
        <div className={stepTooltipBox} style={mt10}>
          （
          {stepTooltip ? `最近一次更新：${stepTooltip}` : '所有内容将实时保存'}
          ）
        </div>
      </div>
      <div className={stepFormBox} style={mt20}>
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          onFieldsChange={fieldsChange}
        >
          {props.children}
        </Form>
        <div className={actionBtnBox} style={mt20}>
          <Button type="primary" style={mr20} onClick={goForNext}>
            下一步
          </Button>
          {props.stepCurrent !== 0 ? (
            <Button type="primary" style={mr20} onClick={goForPrev}>
              上一步
            </Button>
          ) : (
            ''
          )}
          <Button style={mr20} onClick={goForNext}>
            保存草稿
          </Button>
          <Button style={mr20} onClick={cancel}>
            取消
          </Button>
        </div>
      </div>
    </div>
  );
});
export default StepForm;
